<template>
  <view class="root">
    <text
      :class="[
        `tips ellipsis lh-60 pl-12 pr-12 bgc-fff9ea fs-22 color-e48100 fw-500 text-center`,
      ]"
    >
      {{ communityDetail.notice || "--" }}
    </text>
    <view class="community-container bgc-fff pl-30 pt-16 pr-30">
      <view class="subject fd-row ai-center">
        <image
          class="community-avatar"
          mode="aspectFill"
          @click="previewImage([communityDetail.avatar || defaultAvatar])"
          :src="communityDetail.avatar || defaultAvatar"
        />
        <view class="community-content ml-20 pb-12 f1">
          <view class="fd-row">
            <text class="title fs-30 color-333 fw-600 f1">
              {{ communityDetail.name || "--" }}
            </text>
            <image
              v-if="communityDetail.tel"
              @click="call"
              class="width-50 height-50"
              :src="`/static/imgs/icon-call${
                communityDetail.tel ? 'ed' : ''
              }.png`"
            />
          </view>

          <view
            v-if="communityDetail.address"
            class="address fd-row ai-center mt-8 f1"
          >
            <image
              class="flex-shrink width-18 height-22"
              src="/static/imgs/icon-position0.png"
            />
            <text class="ellipsis fs-24 color-8f9aa8 ml-10">
              {{ communityDetail.address || "--" }}
            </text>
          </view>
          <view class="fd-row ai-end">
            <view :style="{ lineHeight: 2 }">
              <view class="fd-row">
                <view class="mr-10 fs-22 fd-row ai-baseline">
                  <text class="color-8f9aa8">关注</text>
                  <text class="color-333 ml-6 mr-6">
                    {{ communityDetail.rssNum || 0 }}
                  </text>
                  <text class="color-8f9aa8">人</text>
                </view>
                <view class="ml-10 fs-22 fd-row ai-baseline">
                  <text class="color-8f9aa8">浏览</text>
                  <text class="color-333 ml-6 mr-6">
                    {{ communityDetail.scanNum || 0 }}
                  </text>
                  <text class="color-8f9aa8">次</text>
                </view>
              </view>

              <text v-if="communityDetail.date" class="color-8f9aa8 fs-20">
                创建时间： {{ communityDetail.date }}
              </text>
            </view>
            <button
              class="fs-26 fd-row ai-center"
              hover-class="btn-hover"
              :plain="true"
              @click="subscription"
              :style="{
                marginRight: 0,
                paddingRight: 0,
                lineHeight: 2,
                border: `none`,
                opacity: communityDetail.isRss ? 0.6 : 1,
                color: communityDetail.isRss ? `#666` : `#4388e7`,
              }"
            >
              <image
                v-if="!!communityDetail.isRss"
                class="width-24 height-18 mr-6"
                src="/static/imgs/icon-hook.png"
              />
              <text> {{ communityDetail.isRss ? "已关注" : "+ 关注" }}</text>
            </button>
          </view>
        </view>
      </view>
      <view class="sticky fs-22 mt-20 mb-4">
        <label
          v-for="(item, index) in communityDetail.top"
          :key="index"
          @click="getTopData"
          class="post mb-16"
        >
          <view>
            <label
              :class="[
                communityDetail.type ? 'community-symbol' : 'group-symbol',
                'br-10',
              ]"
            >
              {{ communityDetail.type ? "置顶" : "社群简介" }}
            </label>
          </view>
          <text
            :class="[
              { ellipsis: communityDetail.type },
              'post-title',
              'lh-40',
              'color-5b6c98',
              'ml-12',
              'f1',
            ]"
          >
            {{ item.text }}
          </text>
        </label>
      </view>

      <view class="fd-row jc-sb pt-16 pb-16">
        <label class="ai-center lh-60 height-60 f1 bgc-f3f3f4 br-30">
          <icons type="search" class="ml-24 mr-20" />
          <input
            class="input f1 height-100percent pr-20 fs-26"
            v-model="searchContent"
            placeholder="输入搜索内容"
            confirm-type="search"
            @input="getPostData"
          />
        </label>
        <navigator
          v-if="communityDetail.type"
          :url="`communityGroup?bid=${bid}`"
          hover-class="opacity-06"
          class="fd-row ml-46 ai-center"
        >
          <text class="fs-30 color-333">更多服务群</text>
          <image
            class="width-16 height-28 ml-12"
            src="/static/imgs/icon-right.png"
          />
        </navigator>
      </view>
    </view>
    <view class="main pb-30">
      <view
        v-for="(postItem, postIndex) in posts.lists"
        :key="postIndex"
        class="post-section"
      >
        <view class="section pl-30 pr-50 pt-26 pb-26 mt-10 fw-500 bgc-fff">
          <view class="title fd-row ai-center">
            <image
              class="user-avatar width-70 height-70 br-circle"
              :src="postItem.avatar || defaultAvatar"
              mode="aspectFill"
            />
            <text class="nickname ml-20 f1 color-5b6c98 fs-26 ellipsis">
              {{ postItem.nickname }}
            </text>
            <text class="color-8f9aa8 fs-24">{{ postItem.time }}</text>
          </view>

          <view class="content ml-90 mt-10">
            <text user-select class="article color-333 fs-30 lh-38">
              {{ postItem.content }}
            </text>

            <view
              v-if="postItem.type == 'image'"
              class="preview-image fd-row mt-24"
            >
              <view
                v-for="(previewItem, previewIndex) in postItem.preview"
                :key="previewIndex"
                class="preview-image-box"
              >
                <image
                  @click="previewImage(postItem.preview, previewIndex)"
                  class="br-8"
                  :src="previewItem"
                  mode="aspectFill"
                />
              </view>
            </view>

            <video
              v-if="postItem.type == 'video'"
              :src="postItem.preview.url"
              controls
              play-btn-position="center"
              :title="postItem.nickname + '发布的视频'"
              class="preview-video mt-24 br-8"
            />
            <view class="operation fd-row ai-center jc-sa mt-28">
              <label
                v-for="(operationItem, operationIndex) in postItem.operations"
                :key="operationIndex"
                @click="operation(postIndex, operationIndex)"
                class="ai-center"
                :style="{ padding: `12rpx` }"
              >
                <image
                  class="width-28 height-28"
                  :src="
                    '/static/imgs/icon-' +
                    (operationItem.isActive
                      ? operationItem.active
                      : operationItem.type) +
                    '.png'
                  "
                />
                <text v-if="operationItem.number" class="ml-12 color-333 fs-24">
                  {{ operationItem.number }}
                </text>
              </label>
            </view>
          </view>
        </view>
      </view>
    </view>
    <label v-if="postsLoading" class="ai-center jc-center">
      <image
        class="width-46 height-46"
        src="/static/imgs/icon-loading.gif"
        mode="aspectFill"
      />
      <text class="color-666 fs-28 ml-18">加载中...</text>
    </label>
    <text
      v-else-if="!posts.lists.length"
      :style="{ lineHeight: 6 }"
      class="color-666 fs-28 ml-18 text-center"
    >
      发一条动态试试吧
    </text>
    <view
      v-if="isTop"
      :url="`/pages/publish?bid=${bid}`"
      hover-class="btn-hover"
      class="posting fixed color-666 fs-28 left-0"
      @click="backPress"
      :style="{
        padding: `6rpx 24rpx`,
        backgroundColor: `#eee`,
        borderRadius: `0 18rpx 18rpx 0`,
        bottom: `90px`,
      }"
    >
      <text>返回</text>
    </view>

    <view
      hover-class="btn-hover"
      class="posting fixed bottom-90 right-0"
      @click="posting"
    >
      <image class="btn-posting" src="/static/imgs/btn-posting.png" />
    </view>

    <popup ref="comment" type="bottom" @change="changeComment">
      <view class="popup-box bgc-f9">
        <view class="title color-000 fs-30 fw-500 text-center lh-100">
          回复帖子
        </view>
        <scroll-view
          class="popup-content"
          scroll-y
          @scrolltoupper="getCommentData"
          :scroll-into-view="`section-${scrollIntoViewIndex}`"
          scroll-with-animation
        >
          <view
            v-for="(item, index) in comment.lists"
            :key="index"
            class="section pl-20 pr-20 pt-12 pb-12 mt-10 ml-30 mr-30 fw-500"
            :id="`section-${index + 1}`"
          >
            <view class="title fd-row ai-center">
              <image
                class="user-avatar width-70 height-70 br-circle"
                :src="item.avatar || defaultAvatar"
                mode="aspectFill"
              />
              <text class="nickname ml-20 f1 color-5b6c98 fs-26 ellipsis">
                {{ item.nickname }}
              </text>
              <text class="color-8f9aa8 fs-24">{{ item.time }}</text>
            </view>

            <view class="content ml-90 mt-10">
              <text class="article color-333 fs-28">{{ item.text }}</text>
            </view>
          </view>
          <label v-if="commentLoading" class="ai-center jc-center">
            <image
              class="width-46 height-46"
              src="/static/imgs/icon-loading.gif"
              mode="aspectFill"
            />
            <text class="color-666 fs-28 ml-18">加载中...</text>
          </label>
          <label
            v-if="!comment.lists.length && !commentLoading"
            class="color-666 fs-28 ml-18 jc-center mt-30"
          >
            暂无评论...
          </label>
        </scroll-view>
        <view
          :style="{ bottom: `${keyboardHeight}px` }"
          :class="[
            `input-wrapper bgc-fff width-100vw fixed fd-row ai-center pt-18 pb-18 pl-20 pr-20`,
          ]"
        >
          <input
            class="comment-input f1 fs-30 input"
            placeholder-class="color-999"
            placeholder="喜欢就评论告诉TA"
            confirm-type="send"
            v-model="sendMsg"
            @confirm="send"
            :adjust-position="false"
          />
          <button
            @click="send"
            class="bgc-8ec5fc color-fff fs-30 send-btn ml-12"
          >
            发送
          </button>
        </view>
      </view>
    </popup>
  </view>
</template>
<script>
  import popup from "@/components/popup";
  import icons from "@/components/icons";
  let debounce;
  export default {
    components: { popup, icons },
    data() {
      return {
        defaultAvatar: "/static/imgs/default-avatar.png",
        communityDetail: { top: [] },
        posts: {
          page: 1,
          lists: [],
        },
        comment: {
          page: 1,
          lists: [],
        },
        sendMsg: "",
        searchContent: "",
        commentLoading: true,
        postsLoading: true,
        flag: false,
        keyboardHeight: 0,
        bid: 0,
        isTop: false,
        scrollIntoViewIndex: 0,
        userInfo: uni.getStorageSync("userInfo") || {},
      };
    },
    onLoad({ id }) {
      this.bid = id;
      this.init();
      uni.$on("refresh", this.init);

      uni.fetch("/api/bbs/community_detail", {
        data: { bid: this.bid },
        success: (res) => {
          this.communityDetail = res;
          uni.setNavigationBarTitle({
            title: res.type ? "社区" : "社群",
          });
        },
      });

      uni.onKeyboardHeightChange((res) => {
        this.keyboardHeight = res.height;
      });
    },
    onUnload() {
      uni.$off("refresh");
      uni.offKeyboardHeightChange();
    },
    onShareAppMessage() {
      const { name, bid } = this.communityDetail;
      return {
        title: name || "家元",
        path: `/pages/postBar?id=${bid || this.bid}`,
      };
    },
    onShareTimeline() {
      const { name, bid, avatar } = this.communityDetail;
      return {
        imageUrl: avatar,
        imagePreviewUrl: avatar,
        title: name || "家元",
        path: `/pages/postBar?id=${bid || this.bid}`,
      };
    },
    onPullDownRefresh() {
      this.isTop ? this.getTopData(true) : this.getPostData(true);
    },
    onReachBottom() {
      !this.isTop && this.getPostData();
    },
    methods: {
      async posting() {
        if (debounce) return;
        debounce = true;
        await this.authUserInfo();
        debounce = false;
        uni.navigateTo({ url: `/pages/publish?bid=${this.bid}` });
      },
      async authUserInfo() {
        if (this.userInfo.avatar) return;

        const [fail, result] = await uni.getUserProfile({
          desc: "授权信息用于社区头像及昵称展示",
        });

        if (fail) return;

        const { avatarUrl: img, nickName: nickname } = result.userInfo;

        uni.fetch("/api/user/upinfo", {
          data: { img, nickname },
          success: (res) => {
            this.userInfo = Object.assign(uni.getStorageSync("userInfo"), res);
            uni.setStorage({
              key: "userInfo",
              data: this.userInfo,
            });
          },
        });
      },
      backPress() {
        if (this.isTop) {
          this.init();
          return;
        }
        uni.$emit("refresh", { data: "community", msg: "刷新数据" });
      },
      subscription() {
        if (this.flag) return;
        this.flag = true;
        uni.fetch("/api/bbs/rss", {
          data: { bid: this.bid },
          success: (res) => {
            this.communityDetail.isRss = !this.communityDetail.isRss;
            this.flag = false;
          },
        });
      },
      init() {
        this.isTop = false;
        this.posts.page = 1;
        this.posts.lists = [];
        this.getPostData();
      },
      call(item) {
        uni.makePhoneCall({
          phoneNumber: this.communityDetail.tel,
        });
      },
      getTopData(e) {
        if (!this.communityDetail.type) return;
        uni.fetch("/api/login/zhiding", {
          data: { bid: this.bid },
          complete: () => e && setTimeout(uni.stopPullDownRefresh, 1200),
          success: (res) => {
            this.isTop = true;
            this.posts = res;
          },
        });
      },
      getPostData(e) {
        this.postsLoading = true;
        if (e) {
          this.posts.page = 1;
          this.posts.lists = [];
        }
        if (!this.posts.page) {
          this.postsLoading = false;
          return;
        }
        uni.fetch("/api/login/note_lists", {
          data: {
            bid: this.bid,
            page: this.posts.page,
            keyword: this.searchContent,
            limit: 10,
          },
          complete: () => e && setTimeout(uni.stopPullDownRefresh, 1500),
          success: (res) => {
            this.posts.page = res.page;
            this.posts.lists.push(...res.lists);
            this.postsLoading = false;
            e && uni.stopPullDownRefresh();
          },
        });
      },
      getCommentData() {
        this.commentLoading = true;
        if (!this.comment.page) {
          this.commentLoading = false;
          return;
        }
        uni.fetch("/api/login/comment_lists", {
          data: {
            tid: this.posts.lists[this.postIndex].tid,
            page: this.comment.page,
            limit: 10,
          },
          success: (res) => {
            this.comment.page === 1 &&
              (this.scrollIntoViewIndex = res.lists.length);

            this.comment.page = res.page;
            this.commentLoading = false;
            this.comment.lists.unshift(...res.lists.reverse());
          },
        });
      },

      async operation(postIndex, operationIndex) {
        const item = this.posts.lists[postIndex],
          operation = item.operations[operationIndex];
        switch (operation.type) {
          case "like":
          case "dislike":
            uni.fetch("/api/bbs/note_act", {
              data: {
                tid: item.tid,
                type: operation.type == "like" ? 0 : 1,
              },
            });
            operation.isActive = !operation.isActive;
            operation.isActive ? operation.number++ : operation.number--;
            break;
          case "comment":
            if (debounce) return;
            debounce = true;
            this.postIndex = postIndex;
            this.comment.page = 1;
            this.comment.lists = [];
            this.scrollIntoViewIndex = 0;
            this.getCommentData();
            await this.authUserInfo();
            debounce = false;
            this.popupSwitch(true, operation.type);
            break;
          default:
            uni.showActionSheet({
              itemList: operation.moreMenu.map((item) => item.name),
              success: (res) => {
                switch (operation.moreMenu[res.tapIndex].mode) {
                  case "delete":
                    let list = this.posts.lists;
                    uni.fetch("/api/bbs/note_del", {
                      data: {
                        tid: list[postIndex].tid,
                      },
                      success: (res) => {
                        list.splice(postIndex, 1);
                        uni.showToast({ title: "已删除" });
                      },
                    });
                    break;
                  case "report":
                    uni.showToast({ title: "已举报" });
                    break;
                  case "shield":
                    uni.showToast({ title: "已屏蔽" });
                    this.posts.lists.splice(postIndex, 1);
                    break;
                  default:
                    break;
                }
              },
            });
        }
      },
      previewCommunityAvatar() {
        uni.previewImage({
          urls: [this.communityDetail.avatar || this.defaultAvatar],
          indicator: "none",
        });
      },
      previewImage(urls, current = 0) {
        uni.previewImage({ current, urls });
      },
      send() {
        if (this.sendMsg) {
          uni.fetch("/api/bbs/comment", {
            data: {
              tid: this.posts.lists[this.postIndex].tid,
              text: this.sendMsg,
            },
            success: (res) => {
              this.sendMsg = "";
              this.posts.lists[this.postIndex].operations[2].number++;
              this.comment.lists.push(res);
              this.scrollIntoViewIndex = this.comment.lists.length;
            },
          });
        } else {
          uni.showToast({ title: "你还没有输入内容", icon: "none" });
        }
      },
      popupSwitch(turn, ref) {
        this.$refs[ref][turn ? "open" : "close"]();
      },
      changeComment(e) {
        // console.log(e);
      },
    },
  };
</script>

<style scoped>
  .bgc-f3f3f4 {
    background-color: #f3f3f4;
  }
  .header,
  .posting {
    z-index: 99;
  }
  .community-container {
    border-bottom: 1rpx solid #ebebeb;
  }
  .community-avatar {
    width: 150rpx;
    height: 150rpx;
  }
  .community-content {
    border-bottom: 1rpx solid #ebebeb;
    overflow: hidden;
  }

  .group-symbol {
    color: #4388e7;
    border: 1rpx solid #4388e7;
  }
  .group-symbol,
  .community-symbol {
    height: 40rpx;
    line-height: 40rpx;
    padding: 0 16rpx;
  }
  .community-symbol {
    color: #fff;
    background: linear-gradient(90deg, #8ec5fc, #4388e7);
  }
  .preview-image {
    flex-wrap: wrap;
  }

  .preview-image-box {
    position: relative;
    width: calc((100% - 36rpx) / 3);
    padding-bottom: calc((100% - 36rpx) / 3);
    margin: 6rpx;
    height: 0;
  }
  .preview-image image {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
  }
  .btn-posting {
    width: 134rpx;
    height: 134rpx;
  }
  .preview-video {
    width: auto;
    height: 200px;
    margin-right: 250rpx;
    position: relative;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
    overflow: hidden;
  }

  .popup-box {
    border-top-left-radius: 12rpx;
    border-top-right-radius: 12rpx;
  }

  .popup-box .popup-content {
    height: 60vh;
    padding-bottom: 60px;
  }
  .input-wrapper {
    z-index: 999;
    height: 60px;
  }
  .comment-input {
    border: 1rpx solid #aaa;
    border-radius: 33rpx;
    padding: 12rpx 30rpx;
  }

  .send-btn {
    justify-content: center;
    line-height: 2;
    padding-left: 30rpx;
  }

  .article {
    word-break: break-all;
  }
</style>